const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const CleanWebpackPlugin = require('clean-webpack-plugin');
const merge = require('webpack-merge');
const devConfig = require('./webpack.dev.js');
const prodConfig = require('./webpack.prod.js');

const commonConfig = {
    entry: {
        main: './src/index.js'
    },
    output: {
        path: path.resolve(__dirname, 'dist')
    },
    module: {
        rules: [{
                test: /\.js$/,
                exclude: /node_modules/,
                loader: 'babel-loader'
            },
            {
                test: /\.(jpg|png|gif)$/,
                use: {
                    loader: 'url-loader',
                    options: {
                        name: '[name]_[hash].[ext]',
                        outputPath: 'images/',
                        limit: 10240
                    }
                }
            },
            {
                test: /\.(eot|ttf|svg)$/,
                use: {
                    loader: 'file-loader'
                }
            }
        ]
    },
    plugins: [
        new HtmlWebpackPlugin({
            template: 'src/index.html'
        }),
        new CleanWebpackPlugin(['dist']),
    ],
    // 根据代码,自动将代码进行分割,比如lodash.js
    optimization: {
        usedExports: true,
        runtimeChunk: {
            name: "runtime"
        },
        splitChunks: {
            chunks: "all",
            // minSize: 0, // 
            // minChunks: 1, //如果引入大于等于1次就会代码分割
            // maxAsyncRequests: 5,
            // maxInitialRequests: 3,
            // automaticNameDelimiter: '~',
            // name: true,
            // // 同步的代码会走cacheGroups这个配置内容
            // // cacheGroups是缓存组的意思,如果打包两个组件库lodash和jquery,并且想放在一个文件里
            // // 就会等两个都打包完放在一个文件中
            cacheGroups: {
                vendors: {
                    test: /[\\/]node_modules[\\/]/,
                    priority: -10, // 优先级,比如jquery既符合vendors组的要求,也符合default组的要求,那么priority大的就会放在这个组的文件里
                    name: 'vendors'  // 如果是同步代码就可以设置该配置,如果是异步的会报错
                }
            //     default:  {
            //         priority: -20,
            //         reuseExistingChunk: true, // 如果有某个模块已经在另外一个文件中被打包过,那么再使用该文件时,会重复只用之前打包过的文件
            //         // filename:'common.js'
            //     }
            }
        }
    },
    performance: false
}
console.log('process.env.NODE_ENV', process.env.NODE_ENV);
module.exports = () => {
    if (process.env.NODE_ENV === 'production') {
        return merge(commonConfig, prodConfig)
    } else {
        return merge(commonConfig, devConfig)
    }
}